import json
from datetime import datetime


from django.http import JsonResponse
from django.views import View

from apps.house.models import House
from apps.order.models import Order
from apps.users.models import User
from iHome.utils.view import LoginRequiredJSONMixin


class OrderView(View):
    def post(self, request):
        # user = User.objects.get(pk=1)
        # 接收参数
        house_id = json.loads(request.body).get('house_id')
        start_date = json.loads(request.body).get('start_date')
        end_date = json.loads(request.body).get('end_date')
        # 判空
        if not all([house_id, start_date, end_date]):
            return JsonResponse({"errno": "4001", "errmsg": "DBERR"})
        try:
            house = House.objects.get(pk=house_id)
        except Exception as e:
            return JsonResponse({"errno": "4004", "errmsg": "house_id不存在"})

        # 判断房屋数目
        if not house.room_count:
            return JsonResponse({"errno": "4004", "errmsg": "暂无房屋预定"})

        # 修改时间格式
        start_date = datetime.strptime(start_date, '%Y-%m-%d')
        end_date = datetime.strptime(end_date, '%Y-%m-%d')
        assert start_date < end_date, Exception("开始日期大于结束日期")
        # 计算入住天数
        days = (end_date - start_date).days
        # 创建订单
        order = Order.objects.create(
            user=request.user,
            house=house,
            begin_date=start_date,
            end_date=end_date,
            days=days,
            house_price=house.price,
            amount=house.price * days,
            comment='',
            status="WAIT_ACCEPT",
        )

        return JsonResponse({"data": {'order_id': order.pk}, "errno": "0", "errmsg": "ok"})

        # user = User.objects.get(pk=1)
    def get(self,request):
        # 接收参数
        role = request.GET.get('role')
        # 校验参数
        if not role:
            return JsonResponse({"errno": "4001", "errmsg": "DBERR"})
        if role not in ('custom', 'landlord'):
            return JsonResponse({"errno": "4001", "errmsg": "DBERR"})
        try:
            if "custom" == role:  # 房客订单查询
                orders = Order.objects.filter(user=request.user).order_by('-create_time')
            elif "landlord" == role:  # 房东订单查询
                # 1. 先查出当前登录用户的所有的房屋, House
                houses = House.objects.filter(user=request.user)
                # 2. 取到所有的房屋id
                houses_ids = [house.id for house in houses]
                # 3. 从订单表中查询出房屋id在第2步取出来的列表中的房屋
                orders = Order.objects.filter(house_id__in=houses_ids).order_by('-create_time')
        except Exception as e:
            return JsonResponse({'errno': 0, 'errmsg': "数据查询错误"})
        # 订单列表
        orders_list = []
        for order in orders:
            orders_list.append({
                "amount": order.amount,
                "comment": order.comment,
                "ctime": order.create_time.strftime("%Y-%m-%d"),
                "days": order.days,
                "end_date": order.end_date.strftime("%Y-%m-%d"),
                "img_url": order.house.index_image_url,
                "order_id": order.pk,
                "start_date": order.begin_date.strftime("%Y-%m-%d"),
                "status": order.status,
                "title": order.house.title
            })

        # 拼接数据
        data_dict = {
            'data': {
                'orders': orders_list
            },
            'errmsg': 'ok',
            'errno': '0'
        }
        return JsonResponse(data_dict)




    # 接单拒单
    '''
    请求方式: PUT
    请求路径:  api/v1.0/orders/
    请求参数:  action  string   必传   订单操作类型（接单/拒单）
             order_id   int    必传   订单号
             reason   string   非必传   拒单原因
    响应内容: errno: 0代表成功
             errmsg: 提示信息
    '''
    def put(self, request):
        # 1.解析参数
        user = request.user
        json_dict = json.loads(request.body)
        action = json_dict.get("action")
        order_id = json_dict.get("order_id")
        # 校验参数
        if not all([action, order_id]):
            return JsonResponse({"errno": 4103, "errmsg": '参数不齐'})
        # 判断订单操作类型
        if action not in ("accept", "reject"):
            return JsonResponse({"errno": 4103, "errmsg": '参数错误'})
        # 2.查询订单
        try:
            order = Order.objects.get(id = order_id, status= "WAIT_ACCEPT")
        except Exception as e:
            print(e)
            return JsonResponse({"errno": 4002, "errmsg": '未查询到订单!'})
        # 判断房东是否是当前登录用户
        if user != order.house.user:
            return JsonResponse({"errno": 4105, "errmsg": '无操作权限!'})

        #　修改订单状态
        if action == "accept":
            order.status = "WAIT_COMMENT"
        elif action == "reject":
            order.status = "REJECTED"
            reason = json_dict.get("reason")
            if not reason:
                return JsonResponse({"errno": 4103, "errmsg": '请填写拒单原因'})
            # 保存原因
            order.comment = reason

        # 提交订单
        try:
            order.save()
        except Exception as e:
            print(e)
            return JsonResponse({"errno": 4001, "errmsg": '请填写拒单原因'})

        # 返回数据
        return JsonResponse({"errno": 0, "errmsg":'ok'})


# 评价订单
'''
请求方式: PUT
请求路径: api/v1.0/orders/comment/
请求参数:  comment   string  必传   评论内容
         order_id   int    必传   订单号
响应内容: errno: 0代表成功
         errmsg: 提示信息
'''
class CommentView(LoginRequiredJSONMixin,View):
    def put(self, request):
        # 1.解析参数
        json_dict = json.loads(request.body)
        order_id = json_dict.get("order_id")
        comment = json_dict.get("comment")
        # 2.校验参数
        try:
            order = Order.objects.get(id = order_id, status = "WAIT_COMMENT")
        except Exception as e:
            print(e)
            return JsonResponse({"errno": 4001, "errmsg": "订单不存在！"})
        # 3.主业务逻辑
        order.comment = comment,
        order.status = "COMPLETE"

        try:
            order.save()
        except Exception as e:
            print(e)
            return JsonResponse({"errno": 4001, "errmsg": "数据保存失败！"})

        # 返回数据
        return JsonResponse({"errno": 0, "errmsg": "ok"})
